#include <ArduinoWebsockets.h>
#include <TJpg_Decoder.h>
#include <TFT_eSPI.h>

TFT_eSPI tft = TFT_eSPI();
TFT_eSprite clk = TFT_eSprite(&tft);

using namespace websockets;
WebsocketsServer server;
WebsocketsClient client;

const int lightcol = 0xffff; // 白色
const int darkcol = 0x0000;  // 黑色

// 解码JPEG并显示
bool tft_output(int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t *bitmap)
{
    if (y >= tft.height())
        return 0;
    tft.pushImage(x, y, w, h, bitmap);
    return 1;
}

void TFT_init()
{
    tft.begin();
    tft.setRotation(1);
    tft.setSwapBytes(true);          // We need to swap the colour bytes (endianess)
    TJpgDec.setJpgScale(1);          // The jpeg image can be scaled by a factor of 1, 2, 4, or 8
    TJpgDec.setCallback(tft_output); // 图片解码
    tft.fillScreen(darkcol);         // 清屏
}

void Websocket(void *pt)
{
    TFT_init();
    server.listen(8888);

    while (1)
    {
        if (server.poll()) // 检测是否有数据可读取
        {
            client = server.accept();
        }

        if (client.available())
        {
            client.poll();
            WebsocketsMessage msg = client.readBlocking(); // 接收数据

            uint32_t t = millis();
            TJpgDec.drawJpg(0, 0, (const uint8_t *)msg.c_str(), msg.length()); // Draw the image, top left at 0,0

            t = millis() - t; // 测试输出渲染时间
            Serial.print(t);
            Serial.println(" ms");
            taskYIELD();
        }
    }
}